﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Fashion.ViewModels;
using Fashion.Models;
using System.Collections;
using Valentica.Libraries;
using System.IO;
using System.Data.SqlClient;

namespace Fashion.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        private FashionEntities1 FashionDB = new FashionEntities1();
        private int UsersPerPage = 10;

        public ActionResult Index()
        {
            if (Session["admin"] != null)
                return RedirectToAction("MainPage");
            else
                Session["admin"] = new User();

            return View();
        }

        [HttpPost]
        public ActionResult Index(User admin)
        {
            try
            {
                var user = FashionDB.Users.Single(u => u.Username == admin.Username && u.Password == admin.Password);

                if (user != null && (user.RoleID == 2 || user.RoleID == 1))
                {
                    Session["admin"] = user;
                    return RedirectToAction("MainPage");
                }
            }
            catch (Exception)
            {
                ViewData["error"] = "User does not exist";
                return View();
            }

            ViewData["error"] = "Login failed. Try again.";
            return View();
        }

        public ActionResult Logout()
        {
            if (Session["admin"] != null)
            {
                Session.Clear();
            }

            return Index();
        }

        public ActionResult MainPage()
        {
            if (Session["admin"] != null)
            {
                StatisticsViewModel viewModel = new StatisticsViewModel();
                return View(viewModel);
            }

            return RedirectToAction("Index");
        }

        public ActionResult Orders()
        {
            if (Session["admin"] != null)
            {
                string pageString = "";
                OrderDetailModel viewModel = new OrderDetailModel();
                try
                {
                    pageString = Request.Url.Segments[3];

                }
                catch (Exception)
                {
                    pageString = null;
                }

                if (pageString != null)
                    viewModel.ViewAllOrders();
                else
                    viewModel.ViewTodayOrders();

                return View(viewModel);
            }

            return RedirectToAction("Index");
        }

        public ActionResult EditOrder(int orderID)
        {
            if (Session["admin"] != null)
            {
                OrderDetailModel viewModel = new OrderDetailModel();
                viewModel.GetOrder(orderID);

                return View(viewModel);
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult EditOrder(OrderDetailModel model)
        {
            if (Session["admin"] != null)
            {
                double temp = model.orderDetails.Quantity * model.orderDetails.Price;
                double total = Convert.ToDouble(Request.Form["TotalPrice"]);
                if (temp == total)
                {
                    try
                    {
                        var orderDetail = FashionDB.OrderDetails.Single(o => o.OrderID == model.orderDetails.OrderID);
                        orderDetail.Quantity = model.orderDetails.Quantity;
                        orderDetail.Price = model.orderDetails.Price;
                        var order = FashionDB.Orders.Single(o => o.OrderID == model.orderDetails.OrderID);
                        order.TotalPrice = total;
                        FashionDB.SaveChanges();
                    }
                    catch (Exception)
                    {
                        return View();
                    }
                }

                OrderDetailModel orders = new OrderDetailModel(model.orderDetails.OrderID);

                return View(orders);
            }

            return RedirectToAction("Index");
        }

        public ActionResult UserPage()
        {
            if (Session["admin"] != null)
            {
                return View();
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult UserPage(User newUser)
        {
            if (Session["admin"] != null)
            {
                newUser.Avatar = "avatar.jpg";
                newUser.RegisterDate = DateTime.Today;

                try
                {
                    FashionDB.AddToUsers(newUser);
                    FashionDB.SaveChanges();
                }
                catch (Exception)
                {
                    //error display here
                    return View();
                }

                return RedirectToAction("UserPage");
            }

            return RedirectToAction("Index");
        }

        public ActionResult UserDetail(int uid)
        {
            if (Session["admin"] != null)
            {
                var userModel = FashionDB.Users.Single(u => u.UserID == uid);

                return View(userModel);
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult UserDetail(User newUser)
        {
            if (Session["admin"] != null)
            {
                var user = FashionDB.Users.Single(u => u.UserID == newUser.UserID);
                try
                {
                    if (!string.IsNullOrWhiteSpace(newUser.FirstName))
                        user.FirstName = newUser.FirstName;
                    if (!string.IsNullOrWhiteSpace(newUser.LastName))
                        user.LastName = newUser.LastName;
                    if (!string.IsNullOrWhiteSpace(newUser.Email))
                        user.Email = newUser.Email;
                    if (!string.IsNullOrWhiteSpace(newUser.AddressLine1))
                        user.AddressLine1 = newUser.AddressLine1;
                    if (!string.IsNullOrWhiteSpace(newUser.AddressLine2))
                        user.AddressLine2 = newUser.AddressLine2;
                    if (!string.IsNullOrWhiteSpace(newUser.City))
                        user.City = newUser.City;
                    if (!string.IsNullOrEmpty(newUser.PostalCode))
                        user.PostalCode = newUser.PostalCode;
                    if (!string.IsNullOrWhiteSpace(newUser.Phone))
                        user.Phone = newUser.Phone;
                    if (!string.IsNullOrWhiteSpace(newUser.Avatar))
                        user.Avatar = newUser.Avatar;

                    FashionDB.SaveChanges();
                }
                catch
                {
                    //error here
                }

                return View(newUser);
            }

            return RedirectToAction("Index");
        }

        public ActionResult FindUser(string username, int page=1)
        {
            if (Session["admin"] != null)
            {
                Pagination pagination = new Pagination(true);

                pagination.CurPage = page;
                pagination.PerPage = UsersPerPage;
                int start = (page - 1) * pagination.PerPage;
                int offset = pagination.PerPage;

                UserSearchViewModel searchModel = new UserSearchViewModel();
                List<User> users = searchModel.SearchByUsername(username, start, offset);
                int totalUsers = searchModel.totalUsers;

                string link = "/Admin/FindUser?username=" + username;
                pagination.BaseUrl = link;
                pagination.TotalRows = totalUsers;

                pagination.PrevLink = "Prev";
                pagination.NextLink = "Next";

                pagination.LoadPaginationXml("\\Content\\Pagination.xml");

                string pageLinks = pagination.GetPageLinks();


                ViewData["totalUsers"] = totalUsers;
                ViewData["pageLinks"] = pageLinks;

                var viewModel = new UserSearchViewModel
                {
                    Users = users
                };

                return View(viewModel);
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult FindUser(FormCollection form)
        {
            if (Session["admin"] != null)
            {
                int page = 1;

                string username = form["username"];
                Pagination pagination = new Pagination(true);

                pagination.CurPage = page;
                pagination.PerPage = UsersPerPage;
                int start = (page - 1) * pagination.PerPage;
                int offset = pagination.PerPage;

                UserSearchViewModel searchModel = new UserSearchViewModel();
                List<User> users = searchModel.SearchByUsername(username, start, offset);
                int totalUsers = searchModel.totalUsers;

                string link = "/Admin/FindUser?username=" + username;
                pagination.BaseUrl = link;
                pagination.TotalRows = totalUsers;

                pagination.PrevLink = "Prev";
                pagination.NextLink = "Next";

                pagination.LoadPaginationXml("\\Content\\Pagination.xml");

                string pageLinks = pagination.GetPageLinks();


                ViewData["totalUsers"] = totalUsers;
                ViewData["pageLinks"] = pageLinks;

                var viewModel = new UserSearchViewModel
                {
                    Users = users
                };

                return View(viewModel);
            }

            return RedirectToAction("Index");
        }

        public ActionResult Manage(int page=1)
        {
            if (Session["admin"] != null)
            {
                Pagination pagination = new Pagination(true);
                pagination.BaseUrl = "/Admin/Manage?ViewProducts";
                pagination.CurPage = page;
                pagination.PerPage = 20;

                int start = (page - 1) * pagination.PerPage;
                int offset = pagination.PerPage;

                ProductDetailViewModel viewModel = new ProductDetailViewModel();
                viewModel.getListProducts(start, offset);

                pagination.TotalRows = viewModel.totalProducts;


                pagination.PrevLink = "Prev";
                pagination.NextLink = "Next";

                pagination.LoadPaginationXml("\\Content\\Pagination.xml");

                string pageLinks = pagination.GetPageLinks();

                ViewData["totalProducts"] = viewModel.totalProducts;
                ViewData["products"] = viewModel.ProductList;
                ViewData["pageLinks"] = pageLinks;

                return View(viewModel);
            }

            return RedirectToAction("Index");
        }

        public ActionResult AddProduct()
        {
            if (Session["admin"] != null)
            {
                AddProductViewModel viewModel = new AddProductViewModel();
                return View(viewModel);
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Create(string ProductName, int BrandID, int CategoryID, string Description, double Price, HttpPostedFileBase ImageList, string Sex, int ColorID, List<string> SizeList)
        {
            if (Session["admin"] != null)
            {
                //Get color's name
                string Color = (from color in FashionDB.Colors
                                where color.ColorID == ColorID
                                select color.Name).First();

                //Upload product's image
                var temp = "";
                if (Sex == "Female")
                    temp = "Women";
                else
                    temp = "Men";
                var filename = "";

                if (ImageList.ContentLength > 0)
                {

                    //filename = DateTime.Now.ToString("YYYY-MMM-d-HH-mm-ss");
                    filename = ProductName;
                    var extension = Path.GetExtension(ImageList.FileName);
                    filename = filename + "_" + Color + extension;

                    var path = Path.Combine(Server.MapPath("~/Content/" + temp), filename);
                    ImageList.SaveAs(path);
                }
                var dynamicPath = temp + "/" + filename;

                Product product = new Product();
                product.BrandID = BrandID;
                product.CategoryID = CategoryID;
                product.Description = Description;
                product.ImageList = dynamicPath;
                product.Price = Price;
                product.ProductName = ProductName;
                product.Sex = Sex;

                //Automatically generated value
                product.DateAdded = DateTime.Today;
                product.Likes = 0;
                product.Rating = 0;

                FashionDB.AddToProducts(product);
                FashionDB.SaveChanges();

                ProductDetail productDetail = new ProductDetail();
                productDetail.ColorID = ColorID;

                //Parse SizeList into form "S;M;L;XL"
                string size = SizeList[0];
                for (int i = 1; i < SizeList.Count(); ++i)
                {
                    size = ";" + SizeList[i];
                }

                productDetail.SizeList = size;
                productDetail.ProductID = product.ProductID;

                FashionDB.AddToProductDetails(productDetail);
                FashionDB.SaveChanges();

                string temp_url = "/Admin/EditProduct?pid=" + product.ProductID;
                return Redirect(temp_url);
            }

            return RedirectToAction("Index");
        }

        public ActionResult EditProduct(int pid)
        {
            if (Session["admin"] != null)
            {
                ProductViewModel productModel = new ProductViewModel(pid);

                return View(productModel);
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Update(int ProductID, string ProductName, int BrandID, int CategoryID, string Description, double Price, string Image, IEnumerable<HttpPostedFileBase> ImageLists, int ColorID, string Sex, List<int> ColorList, List<string> SizeList)
        {
            if (Session["admin"] != null)
            {
                //Get color's name
                string Color = (from color in FashionDB.Colors
                                where color.ColorID == ColorID
                                select color.Name).First();

                //Upload product's image
                var temp = "";
                if (Sex == "Female")
                    temp = "Women";
                else
                    temp = "Men";

                var filename = "";
                int index = 0;
                foreach (var ImageList in ImageLists)
                {
                    if (ImageList.ContentLength > 0)
                    {
                        filename = Path.GetFileName(ImageList.FileName);

                        var path = Path.Combine(Server.MapPath("~/Content/" + temp), filename);
                        ImageList.SaveAs(path);
                    }
                }

                var product = FashionDB.Products.Single(p => p.ProductID == ProductID);
                product.ProductName = ProductName;
                product.CategoryID = CategoryID;
                product.BrandID = BrandID;
                product.Description = Description;
                product.ImageList = Image;
                product.Price = Price;
                product.Sex = Sex;

                //Automatically generated value
                product.DateAdded = DateTime.Today;
                product.Likes = 0;
                product.Rating = 0;

                FashionDB.SaveChanges();

                // Update product details
                var productDetails = from details in FashionDB.ProductDetails
                                     where details.ProductID == ProductID
                                     select details;

                //Parse SizeList into form "S;M;L;XL"
                string size = SizeList[0];
                for (int i = 1; i < SizeList.Count(); ++i)
                {
                    size += ";" + SizeList[i];
                }

                index = 0;
                foreach (var item in productDetails)
                {
                    if (index <= ColorList.Count())
                    {
                        item.ColorID = ColorList[index];
                        item.SizeList = size;
                        index += 1;
                    }
                    else
                        break;
                }

                FashionDB.SaveChanges();

                while (index < ColorList.Count())
                {
                    ProductDetail newDetail = new ProductDetail();
                    newDetail.ColorID = ColorList[index];
                    newDetail.SizeList = size;
                    newDetail.ProductID = product.ProductID;
                    FashionDB.AddToProductDetails(newDetail);
                    index += 1;
                }

                FashionDB.SaveChanges();

                string temp_url = "/Admin/EditProduct?pid=" + product.ProductID;
                return Redirect(temp_url);
            }

            return RedirectToAction("Index");
        }

        public ActionResult CMS()
        {
            if (Session["admin"] != null)
            {
                return View();
            }

            return RedirectToAction("Index");
        }

        public ActionResult Statistics()
        {
            if (Session["admin"] != null)
            {
                StatisticsViewModel viewModel = new StatisticsViewModel();
                return View(viewModel);
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Statistics(FormCollection form)
        {
            if (Session["admin"] != null)
            {
                DateTime date = DateTime.Parse(form["registerDate"].ToString());
                StatisticsViewModel viewModel = new StatisticsViewModel(date);

                return View(viewModel);
            }

            return RedirectToAction("Index");
        }

        public ActionResult Settings(string act)
        {
            if (Session["admin"] != null)
            {
                if (act == "backup")
                {
                    SqlConnection connect = null;
                    try
                    {
                        //Connect to DB
                        string con = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=A3Fashion;Integrated Security=True";
                        connect = new SqlConnection(con);
                        connect.Open();
                        //----------------------------------------------------------------------------------------------------

                        //Execute SQL---------------
                        SqlCommand command;
                        command = new SqlCommand(@"backup database A3Fashion to disk ='c:\A3Fashion.bak' with init,stats=10", connect);
                        command.ExecuteNonQuery();
                        //-------------------------------------------------------------------------------------------------------------------------------
                        ViewData["result"] = "BACKUP SUCCESSFULLY.";
                    }
                    catch (Exception)
                    {
                        ViewData["result"] = "ERROR! PLEASE TRY BACKUP AGAIN.";
                    }
                    finally
                    {
                        if (connect != null)
                        {
                            connect.Close();
                        }
                    }
                }
                else if (act == "restore")
                {
                    SqlConnection connect = null;
                    try
                    {
                        //Connect to DB
                        string con = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=A3Fashion;Integrated Security=True";
                        connect = new SqlConnection(con);
                        connect.Open();
                        //----------------------------------------------------------------------------------------------------

                        //Excute SQL----------------
                        SqlCommand command;
                        command = new SqlCommand("use A3Fashion", connect);
                        command.ExecuteNonQuery();
                        command = new SqlCommand(@"restore database A3Fashion from disk = 'c:\Fashion.bak'", connect);
                        command.ExecuteNonQuery();
                        ViewData["result"] = "RESTORE SUCCESSFULLY.";
                        //-------------------------------------------------------------------------------------------------------------------------------
                    }
                    catch (Exception)
                    {
                        ViewData["result"] = "ERROR! PLEASE TRY RESTORE AGAIN.";
                    }
                    finally
                    {
                        if (connect != null)
                        {
                            connect.Close();
                        }
                    }
                }

                return View();
            }

            return RedirectToAction("Index");
        }

    }
}
